from django.contrib.syndication.feeds import Feed
from django.contrib.syndication.feeds import FeedDoesNotExist
from django.core.exceptions import ObjectDoesNotExist
from django.utils.feedgenerator import Atom1Feed
from django.conf import settings


from bl_g.models import Entry, Category

class LatestEntries(Feed):
    title = "%s: latest blog entries" % settings.APP_NAME
    link = "/blog/"
    description = "Latest blog entries for %s." % settings.APP_NAME

    def items(self):
        return Entry.published_objects.order_by('-published')[:settings.FEED_ITEMS]

class AtomLatestEntries(LatestEntries):
    feed_type = Atom1Feed
    subtitle = LatestEntries.description

class LatestEntriesByCategory(Feed):
    def get_object(self, bits):
        # In case of "/rss/beats/0613/foo/bar/baz/", or other such clutter,
        # check that bits has only one member.
        if len(bits) != 1:
            raise ObjectDoesNotExist
        return Category.objects.get(slug=bits[0])

    def title(self, obj):
        return settings.BL_G_CATEGORY_PATTERN % obj.category

    def link(self, obj):
        if not obj:
            raise FeedDoesNotExist
        return obj.get_absolute_url()

    def description(self, obj):
        return "Latest blog entries for category %s" % obj.category

    def items(self, obj):
       return Entry.published_objects.filter(category=obj).order_by('-published')[:settings.FEED_ITEMS]

class AtomLatestEntriesByCategory(LatestEntriesByCategory):
    feed_type = Atom1Feed
    subtitle = LatestEntriesByCategory.description
